// ==UserScript==
// @name         cctv-新闻联播-字幕文本
// @namespace    http://tampermonkey.net/
// @version      1.3
// @updateURL    https://gitee.com/zzwuweijun/learning_code/raw/master/JavaScript/_%E6%B5%8F%E8%A7%88%E5%99%A8%E6%89%A9%E5%B1%95/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B2%B9%E7%8C%B4%E8%84%9A%E6%9C%AC/cctv/cctv-%E6%96%B0%E9%97%BB%E8%81%94%E6%92%AD-%E5%AD%97%E5%B9%95%E6%96%87%E6%9C%AC.user.js
// @downloadURL  https://gitee.com/zzwuweijun/learning_code/raw/master/JavaScript/_%E6%B5%8F%E8%A7%88%E5%99%A8%E6%89%A9%E5%B1%95/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B2%B9%E7%8C%B4%E8%84%9A%E6%9C%AC/cctv/cctv-%E6%96%B0%E9%97%BB%E8%81%94%E6%92%AD-%E5%AD%97%E5%B9%95%E6%96%87%E6%9C%AC.user.js
// @description   
// @author       You
// @match        https://tv.cctv.com/*
// @match        https://aigc.cctv.com/*
// @icon         https://tv.cctv.com/favicon.ico
// @resource layui.css        https://unpkg.com/layui@2.11.1/dist/css/layui.css
// @require      https://unpkg.com/layui@2.11.1/dist/layui.js
// @grant        GM_xmlhttpRequest
// @grant        GM_getResourceText
// ==/UserScript==

(async function () {
  'use strict';
  // 更改tv.cctv.com页面样式
  let playingVideo = document.querySelector('.playingVideo');
  let _video = document.querySelector('#_video');
  let video = document.querySelector('#video');
  if (!video) return;

  // 添加css样式
  const style = document.createElement("style");
  let scriptText = GM_getResourceText("layui.css");
  scriptText += '.layui-colla-content{font-size: 23px; text-indent: 2em !important; letter-spacing: 1px !important; font-family: KaiTi !important; color: rgb(54 39 39 / 90%) !important;}.layui-colla-content p{line-height: 1.5em;}'
  scriptText = scriptText.replaceAll('../font', 'https://unpkg.com/layui@2.11.1/dist/font'); // 保证图片等路径加载正确
  style.textContent = scriptText;
  document.body.appendChild(style);

  // 按钮-用于打开字幕
  const divText = document.createElement("div");
  divText.id = '_divText_'
  divText.style = 'display: block; width: 130px; padding: 6px; border-radius: 4px; position: fixed; left: 0px; top: 0px; background-color: rgb(89 89 89); z-index: 99999;'
  divText.innerHTML = `
    <button type="button" id='getText' class="layui-btn layui-bg-orange layui-btn" style='width: 100%;'>获取字幕</button> 
    <input type="text" class="layui-input" id="ID-laydate-demo" placeholder="yyyy-MM-dd">`;
  document.body.appendChild(divText);

  // 记录字幕文本
  let content = []

  layui.use(function () {
    var layer = layui.layer;
    var element = layui.element;
    var laydate = layui.laydate;
    var $ = layui.jquery;

    let flag = false;
    function getTextRequest(date) {
      let url = `http://mrxwlb.com/${date.replaceAll(/年|月|日/g, '')}/${date.replaceAll(/\//g, '')}新闻联播文字版/`;
      // console.log(`url`, date, url)
      GM_xmlhttpRequest({
        method: "GET",
        url,
        headers: {
          "Content-Type": "text/html"
        },
        onload: function (response) {
          content = extractContent(response.responseText)
          layer.msg('请求字幕文本成功');
          flag && document.getElementById('getText').click();
          flag = true;
        },
        onerror: function (response) {
          layer.msg('请求字幕文本---失败了');
        },
      });
    }

    // 渲染-日期
    laydate.render({
      elem: '#ID-laydate-demo',
      format: 'yyyy年/MM月/dd日',
      value: new Date(),
      done: function (value) { getTextRequest(value); date = value; }
    });
    let date = document.getElementById('ID-laydate-demo').value;
    getTextRequest(date);

    let index1;
    document.getElementById('getText').addEventListener('click', () => {
      playingVideo && (playingVideo.style.margin = '0 10px 0');
      _video && (_video.style.width = '940px');

      layer.close(index1);
      let htmlS = '';
      content.forEach((item, index) => {
        let t = item.title;
        let p = '';
        if (index == 0) {
          item.texts.push(numberToDate(t, 1) + `<a href="http://mrxwlb.com/" style="color: red;" target="_blank">字幕官网</a>`);
        }
        item.texts && item.texts.length > 0 && item.texts.forEach(item_p => {
          p += `<p>${item_p}</p><br>`;
        })
        htmlS +=
          `<div class="layui-colla-item">
            <div class="layui-colla-title">${t}</div>
            <div class="layui-colla-content layui-show">
              ${p}
            </div>
          </div>`
      })

      index1 = layer.open({
        title: date + `-新闻联播字幕 `,
        type: 1,
        area: ['470px', 'auto'], // 设置弹层的宽高
        offset: ['60px'], // 弹层的偏移坐标
        offset: 'r',
        shade: false, // 不显示遮罩
        content: `
          <button type="button" class="switchCollapse layui-btn layui-bg-normal layui-btn-xs" style='width: 100%;position: sticky; top: 0px;'>切换面板折叠</button>
          <div class="layui-collapse"> ${htmlS} </div>
          `,
        success: function (layero, index, that) {
          element.render('collapse');/* 重置面板渲染 */
          let sCE = document.getElementsByClassName('switchCollapse');
          sCE[sCE.length - 1].addEventListener('click', switchCollapseFun);
          isOpen = true;
        },
        cancel: function (index, layero, that) {
          playingVideo && (playingVideo.style.margin = '0 auto');
          _video && (_video.style.width = '1200px');
          layer.close(index1);
          return false; // 阻止默认关闭行为
        }
      });
    })

    // 切换面板折叠-全部打开或折叠
    let isOpen = true;
    function switchCollapseFun() {
      isOpen || $('.layui-colla-content').addClass('layui-show');
      isOpen && $('.layui-colla-content').removeClass('layui-show');
      isOpen = !isOpen;
    }

  });

  // 提取HTML中的<p>标签内容
  function extractContent(htmlString) {
    // 创建一个临时DOM元素来解析HTML
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlString, 'text/html');
    // 获取所有的p标签
    const pTags = doc.querySelectorAll('.entry-content p');
    const content = [];
    let currentTitle = '';
    let currentTexts = [];
    pTags.forEach(pTag => {
      const strongTag = pTag.querySelector('strong');
      if (strongTag) {
        // 如果有strong标签，将之前的标题和文本存入数组（如果有的话）
        if (currentTitle || currentTexts.length > 0) {
          content.push({
            title: currentTitle,
            texts: [...currentTexts]
          });
          currentTexts = [];
        }
        // 设置新的标题
        currentTitle = strongTag.textContent.trim();
        // 检查p标签中是否有strong标签以外的文本
        const remainingText = pTag.textContent.replace(strongTag.textContent, '').trim();
        if (remainingText) {
          currentTexts.push(remainingText);
        }
      } else {
        // 如果没有strong标签，将文本添加到当前文本数组
        const text = pTag.textContent.trim();
        if (text) {
          currentTexts.push(text);
        }
      }
    });
    // 添加最后一个标题和文本（如果有的话）
    if (currentTitle || currentTexts.length > 0) {
      content.push({
        title: currentTitle,
        texts: [...currentTexts]
      });
    }
    return content;
  }

  // 将字符串 "20250513今日新闻联播主要内容：" 中的日期提取并格式化为 yyyy-xx-zz 的形式
  function numberToDate(str = '', isReplaceOldStr = false) {
    // 使用正则表达式提取日期部分
    const dateMatch = str.match(/\d{8}/);
    const dateStr = dateMatch ? dateMatch[0] : null;
    if (dateStr) {
      // 提取年、月、日
      const year = dateStr.substring(0, 4);
      const month = dateStr.substring(4, 6);
      const day = dateStr.substring(6, 8);

      // 格式化为 yyyy-xx-zz
      const formattedDate = `${year}-${month}-${day}`;
      if (isReplaceOldStr) {
        return str.replace(dateStr, formattedDate);
      }
      return formattedDate;
    } else {
      console.log("未找到日期");
    }
  }
})();